package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // day01完善登录功能
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("Md5Password:{}", md5Password);
        if (!md5Password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }
    /**
     * 新增员工(day02任务一)
     * @param employeeDTO
     */
    @Override
    public void addEmp(EmployeeDTO employeeDTO) {
        log.info("[当前线程],thread:{}",Thread.currentThread().getId());
        Integer status=1;
        LocalDateTime createTime = LocalDateTime.now();
        LocalDateTime updateTime = LocalDateTime.now();

      //  Long empId = BaseContext.threadLocalEmpId.get();
        Long empId = BaseContext.getCurrentId();
        String username = BaseContext.threadLocalEmpUserName.get();
        log.info("[当前线程],thread:{} empId:{},empUsername:{}",Thread.currentThread().getId(),empId,username);

        Long createUser =empId;
        Long updateUser =empId;

        Employee employee = new Employee();
        employee.setName(employeeDTO.getName());
        employee.setUsername(employeeDTO.getUsername());
        employee.setIdNumber(employeeDTO.getIdNumber());
        employee.setSex(employeeDTO.getSex());
        employee.setPhone(employeeDTO.getPhone());
        employee.setStatus(status);
        employee.setCreateTime(createTime);
        employee.setUpdateTime(updateTime);
        employee.setCreateUser(createUser);
        employee.setUpdateUser(updateUser);

        String md5Password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(md5Password);

        log.info("emp:{}",employee);

        employeeMapper.insertEmp(employee);
    }
    /**
     * 员工分页查询(day02任务二)
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult findByPage(EmployeePageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
        Page<Employee> employeePage = employeeMapper.selectByPageAndName(pageQueryDTO.getName());

        PageResult pageResult = new PageResult(employeePage.getTotal(),employeePage.getResult());
        return pageResult;
    }
    /**
     * 启动禁用员工账号(day02任务三)
     * @param status
     * @param id
     */
    @Override
    public void setEmpStatus(Integer status, Integer id) {
        Employee employee =Employee.builder()
                .id((long)id)
                .status(status)
                .build();
        employeeMapper.updateEmp(employee);
    }
    /**
     * 根据ID获取员工信息(day02任务四)
     * @param id
     * @return
     */
    @Override
    public Employee findById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        employee.setPassword("******");
        return employee;
    }
    /**
     * 更新员工(day02任务四)
     * @param employeeDTO
     */
    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);

        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.updateEmp(employee);
    }
}